﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Device.Location;
using System.Linq;
using System.Net;
using System.Reflection;
using System.ServiceModel;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using IndustrialSmokeCalc.SmokeCalcWCF;
using Telerik.Windows.Controls;

namespace IndustrialSmokeCalc
{
    public partial class ChooseCompany : PhoneApplicationPage
    {
        private ObservableCollection<Company> ListCompany;
        private Company SelectedCompany;
        private Location loc;

        public ChooseCompany()
        {
            InitializeComponent();
            listCompany.SetValue(TiltEffect.IsTiltEnabledProperty, true);
            if (listCompany.Items.Count == 0)
            {
                IsVisible(false);
                busyIndicator.IsRunning = true;
            }
            if(DataSingleton.Instance.MapAccessor == "measurement") GetLocation();
            else GetCompanyList();
        }

        private void IsVisible(bool value)
        {
            if (value) txtSearch.Visibility = Visibility.Visible;
            else txtSearch.Visibility = Visibility.Collapsed;
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (DataSingleton.Instance.MapAccessor == "history")
            {
                ApplicationBar.IsVisible = false;
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            listCompany.SelectedIndex = -1;
        }

        private void GetLocation()
        {
            loc = new Location();
            GeoCoordinate geoCoordinate = loc.GetCoordinate();
            double latitude = geoCoordinate.Latitude;
            double longitude = geoCoordinate.Longitude;
            loc.GetAddress(latitude.ToString(), longitude.ToString());
            loc.PropertyChanged += loc_PropertyChanged;
        }

        private void loc_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            GetCompanyList();   
        }

        private void GetCompanyList()
        {
            SmokeCalcClient client = new SmokeCalcClient();
            client.GetCompanyListCompleted += GetCompanyListCompleted;
            string param, value;
            if (DataSingleton.Instance.MapAccessor == "measurement")
            {
                param = "nearby";
                value = loc.City;
                txtEmpty.Text =
                    "Perusahaan tidak terdapat dalam daftar.&#10;Klik Tambah Baru untuk menambahkan perusahaan.";
            }
            else
            {
                param = "user";
                value = DataSingleton.Instance.UserId;
                txtEmpty.Text =
                    "Anda belum pernah melakukan pengamatan.";
            }
            client.GetCompanyListAsync(param, value);
        }

        private void GetCompanyListCompleted(object sender, GetCompanyListCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                ShowExceptionMessage();
            }
            else 
            {
                busyIndicator.IsRunning = false;
                IsVisible(true);
                Thread.Sleep(500);
                ListCompany = e.Result;
                if (ListCompany.Count == 0)
                {
                    txtEmpty.Visibility = Visibility.Visible;
                }
                else listCompany.ItemsSource = ListCompany;
            }
        }

        private void txtSearch_TextChanged(object sender, TextChangedEventArgs e)
        {
            Search();
        }

        private void Search()
        {
            var listSearch = new ObservableCollection<Company>();
            if (!txtSearch.Text.IsEmpty())
            {
                txtEmpty.Visibility = Visibility.Collapsed;
                foreach (var company in ListCompany)
                {
                    if (company.CompanyName.ToLower().Contains(txtSearch.Text.ToLower())
                        || company.CompanyCategory.ToLower().Contains(txtSearch.Text.ToLower())
                        || company.CompanyAddress.ToLower().Contains(txtSearch.Text.ToLower())
                        || company.CompanyCity.ToLower().Contains(txtSearch.Text.ToLower()))
                    {
                        listSearch.Add(company);
                    }
                }
                listCompany.ItemsSource = listSearch;
                if (listSearch.Count == 0)
                {
                    if (DataSingleton.Instance.MapAccessor == "measurement")
                    {
                        txtEmpty.Text =
                            "Perusahaan tidak terdapat dalam daftar.&#10;Klik Tambah Baru untuk menambahkan perusahaan.";
                    }
                    else
                    {
                        txtEmpty.Text = "Perusahaan tidak terdapat dalam daftar.";
                    }
                    txtEmpty.Visibility = Visibility.Visible;
                }
            }
            else
            {
                txtEmpty.Visibility = Visibility.Collapsed;
                listCompany.ItemsSource = ListCompany;
            }
        }

        private void TxtSearch_OnActionButtonTap(object sender, EventArgs e)
        {
            Search();
        }

        private void ShowExceptionMessage()
        {
            MessageBox.Show("Tidak dapat melakukan koneksi ke server.\r\nCoba periksa koneksi internet anda.");
            NavigationService.Navigate(new Uri("/Menu.xaml", UriKind.Relative));
        }

        private void AppBarAdd_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AddCompany.xaml", UriKind.Relative));
        }

        private void listCompany_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listCompany.SelectedIndex >= 0)
            {
                SelectedCompany = listCompany.SelectedItem as Company;
                DataSingleton.Instance.CompanyId = SelectedCompany.CompanyId;
                NavigationService.Navigate(new Uri("/ChimneyMap.xaml", UriKind.Relative));
            }
        }
    }
}